import { login, guestLogin, getUserInfo, getGuestUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const states = {
  token: getToken(),
  role: 'admin',
  userInfo: {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  RESET_STATE: (state) => {
    state.token = getToken()
    state.userInfo = {}
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      if (username === 'admin') {
        login({ username: username.trim(), pwd: password })
          .then((response) => {
            const { data } = response
            commit('SET_TOKEN', data.token)
            commit('SET_ROLE', 'admin')
            setToken(data.token)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      } else {
        guestLogin({ username: username.trim(), pwd: password })
          .then((response) => {
            const { data } = response
            commit('SET_TOKEN', data.token)
            commit('SET_ROLE', 'guest')
            setToken(data.token)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },
  getUserInfo({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      if (state.role === 'admin') {
        getUserInfo({})
          .then((response) => {
            const { data } = response
            commit('SET_USERINFO', data.userInfo)
            dispatch('role/setMenuList', data.menus, { root: true })
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      } else {
        getGuestUserInfo({})
          .then((response) => {
            const { data } = response
            commit('SET_USERINFO', data.userInfo)
            dispatch('role/setMenuList', data.menus, { root: true })
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },
  // user logout
  logout({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state: states,
  mutations,
  actions
}
